package com.axend.aerosense.dev.fragment.checkupdate;

import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.axend.aerosense.base.fragment.MvvmBaseFragment;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.viewmodel.BaseViewModelFactroy;
import com.axend.aerosense.common.base.IHostLayout;
import com.axend.aerosense.common.base.ITitle;
import com.axend.aerosense.common.ui.LoadingDialog;
import com.axend.aerosense.common.util.FragmentUtil;
import com.axend.aerosense.dev.BR;
import com.axend.aerosense.dev.R;
import com.axend.aerosense.dev.databinding.DevFragmentCheckUpdateBinding;
import com.axend.aerosense.dev.entity.FirmwareInfoBean;
import com.axend.aerosense.dev.fragment.DevDeviceSettingsFragment;
import com.axend.aerosense.dev.viewmodel.DevCheckUpdateViewModel;
import com.blankj.utilcode.util.LogUtils;

/**
 * @author ChenHongWei
 * @date :2021/1/8 16:09
 */

public class DevCheckUpdateFragment
        extends MvvmBaseFragment<DevFragmentCheckUpdateBinding, DevCheckUpdateViewModel>
        implements ILoadDataResult<FirmwareInfoBean> {

    public static final String UPGRADE_RESULT = "UPGRADE_RESULT";

    private String radarId = "";
    private String radarFirmwareVersion;
    private String updateRecord = "";

    public static DevCheckUpdateFragment getInstance(){
        DevCheckUpdateFragment fragment = new DevCheckUpdateFragment();
//        Bundle bundle = new Bundle();
//        bundle.putString(ARG_PARAM, str);
//        fragment.setArguments(bundle);   //设置参数
        return fragment;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init();
        setLoadSir(viewDataBinding.devContentView);
        onRetryBtnClick();
    }

    private void init(){
        Bundle bundle = getArguments();
        if (bundle != null){
            radarId = bundle.getString(DevDeviceSettingsFragment.RADAR_ID, "");
        }
        viewModel.setRadarId(radarId);

        viewDataBinding.devBtnBottm.setOnClickListener(v->{
            startUpdate();
        });

        viewModel.pagerState.observe(getViewLifecycleOwner(), integer -> {
            StringBuilder builder = new StringBuilder();
            switch (integer){
                case 1:
                    builder.append("V")
                            .append(radarFirmwareVersion)
                            .append("\n")
                            .append(getString(R.string.dev_up_to_date));
                    viewDataBinding.devTextTip.setText(builder.toString());
                    break;
                case 2:
                    builder.append(getString(R.string.dev_find_new_version))
                            .append(" V")
                            .append(radarFirmwareVersion)
                            .append("\n\n")
                            .append(updateRecord);
                    viewDataBinding.devTextTip.setText(builder.toString());
                    break;
                case 3:
                    builder.append(getString(R.string.dev_download_now));
                    viewDataBinding.devTextTip.setText(builder.toString());
                    break;
                default:
                    viewDataBinding.devTextTip.setText("");
                    break;
            }
        });

        viewModel.isUpdateSuccess.observe(getViewLifecycleOwner(), aBoolean -> {
            toNextPager(aBoolean);
        });
    }

    private void toNextPager(boolean isSuccess){
        //取消屏幕常亮
        DevDeviceUpdateTaskFragment fragment = DevDeviceUpdateTaskFragment.getInstance();
        Bundle bundle = new Bundle();
        bundle.putBoolean(UPGRADE_RESULT, isSuccess);
        fragment.setArguments(bundle);
        FragmentUtil.add(getActivity(), ((IHostLayout) getActivity()).getContentId(), fragment, this, true);
    }

    private void startUpdate(){
        //屏幕常亮
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        viewModel.pagerState.setValue(3);
        viewModel.startUpdate();
    }

    @Override
    public void onResume() {
        super.onResume();
        ((ITitle)getActivity()).setTitle(getString(R.string.dev_check_update));
    }

    @Override
    public int getLayoutId() {
        return R.layout.dev_fragment_check_update;
    }

    @Override
    public int getBindingVariable() {
        return BR.data;
    }

    @Override
    protected DevCheckUpdateViewModel getViewModel() {
        BaseViewModelFactroy<FirmwareInfoBean> factroy = new BaseViewModelFactroy<>(this, this);
        return new ViewModelProvider(this, factroy).get(DevCheckUpdateViewModel.class);
    }

    @Override
    protected void onRetryBtnClick() {
        showLoading();
        viewModel.onLoad();
    }

    @Override
    public void loadDataSuccess(FirmwareInfoBean firmwareInfoBean) {
        if (null == firmwareInfoBean || null == firmwareInfoBean.getRadarInfo()) return;

        radarFirmwareVersion = firmwareInfoBean.getRadarInfo().getVersion();
        boolean update = firmwareInfoBean.getRadarInfo().isUpdate();
        if (firmwareInfoBean.getRadarInfo().isUpgrading()){
            startUpdate();
        }else {
            updateRecord = firmwareInfoBean.getRadarInfo().getDesc();
            viewModel.pagerState.setValue(update ? 2 : 1);
        }
    }

    @Override
    public void loadDataFail(String decs) {
        showFailure(decs);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
}
